package deibay.server.network;


import java.util.Date;
import java.util.Hashtable;
import java.util.LinkedList;
import java.util.Vector;
import java.util.logging.Level;

import deibay.DeibayLogger;
import deibay.server.ServerManager;
import deibay.server.eventargs.RemoveSessionEventArg;
import deibay.server.events.RemoveSessionEvent;

public class ClientSessionActivity implements Runnable{

	private Hashtable<String, Session> sessions = null;
	private boolean keepAlive;
	private int waitSeconds; 
	
	public ClientSessionActivity(Hashtable<String, Session> sessions)
	{
		this.sessions = sessions;
		keepAlive = true;
		waitSeconds = 10;
	}
	
	public synchronized void run() {	
				
		synchronized(sessions)
		{
			while (sessions.isEmpty())
			{
				//System.err.println("OLAAA activity");
				try {
					sessions.wait();
				} catch (InterruptedException e) {
					DeibayLogger.getInstance().getLog().log(Level.SEVERE, "Excepcao ao lancar o wait na thread ClientSessionActivity. \n");
				}
			}
		}
		
		while(keepAlive == true)
		{
			//System.err.println("OLAAA activity");
			
			Vector<Session> toRemove = new Vector<Session>();
			synchronized(sessions)
			{
				Date now = new Date(System.currentTimeMillis());			
				LinkedList<Session> sessionCollect = new LinkedList<Session>(sessions.values());
				for(Session s: (LinkedList<Session>) sessionCollect.clone())
				{				
					if(now.getTime() > s.getLastActivity().getTime()+(waitSeconds*1000))
					{			
						DeibayLogger.getInstance().getLog().log(Level.WARNING, "Sessao do utilizador "+s.getUsername()+" esta sem actividade e sera removida.\n");
						toRemove.add(s);
					}					
				}
			}
			
			for (Session session : toRemove) {
				ServerManager.getInstance().getEventManager().fireEvent(new RemoveSessionEvent(new RemoveSessionEventArg(session)));
			}

			try {
				Thread.sleep(waitSeconds*1000);
			} catch (InterruptedException e) {				
				e.printStackTrace();
			}
		}
		
	}

}
